﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using DonnetSpeech;
using FastReport;
using MINERP.FactoryGrid.COM;
using MINERP.ComControls;

namespace MINERP.FactoryGrid
{
    public partial class FrmMain : FrmParent
    {
        private static int CurSubAreaTypeId = 3;//默认是车间分册分区
        private const string TBGRIDNAME = "AllGridMsg";
        private DataSet _dsResult = new DataSet();
        private string strCon = ConfigurationManager.ConnectionStrings["sqlCon"].ConnectionString;

        public FrmMain()
        {
            InitializeComponent();
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            FrmSelSubArea frmSel = new FrmSelSubArea();
            if (frmSel.ShowDialog()==DialogResult.OK)
            {
                if (frmSel.SelectedSubAreaType>0)
                {
                    CurSubAreaTypeId = frmSel.SelectedSubAreaType;
                    RushGridControl();
                }
                else
                {
                    MessageBox.Show("您没有选择任何分区，全并工具将关闭");
                    this.Close();
                }
               
            }
            else
            {
                MessageBox.Show("您没有选择任何分区，全并工具将关闭");
                this.Close();              
            }
         
        }

        private void RushGridControl()
        {
            using (SqlConnection con = new SqlConnection(strCon))
            {
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }
                var Command = con.CreateCommand();
                Command.CommandText = "GetFactoryGridMeg";
                Command.Parameters.Add(new SqlParameter("@SubAreaType", CurSubAreaTypeId));
                Command.CommandType = CommandType.StoredProcedure;

                SqlDataAdapter da = new SqlDataAdapter(Command);
                if (_dsResult.Tables[TBGRIDNAME] != null)
                    _dsResult.Tables.Remove(TBGRIDNAME);

                da.Fill(_dsResult, TBGRIDNAME);
            }
            if (_dsResult.Tables.Count > 0)
            {
                gridControl1.DataSource = _dsResult.Tables[TBGRIDNAME];
                gridControl1.RefreshDataSource();
                //labelControl2.Text = "总数" + _dsResult.Tables[TBGRIDNAME].Rows.Count;
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            RushGridControl();
        }

        private void layoutView1_DoubleClick(object sender, EventArgs e)
        {
            //双击就显示该格子的详细情况
            var selectRow = layoutView1.GetFocusedDataRow();
            if (selectRow != null)
            {

                //int productCount = Convert.ToInt32(selectRow["ProductCount"]);
                //if (productCount > 0)
                //{
                int gridID = Convert.ToInt32(selectRow["GridId"]);
                if (gridID > 0)
                {
                    FrmShowGridDetail frmD = new FrmShowGridDetail();
                    frmD.GridID = gridID;
                    frmD.ShowDialog();
                }
                //}
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            //查看该产品的这部分有没有放入到格子中，如果有则提示格子号，并刷新，如果没有则跳出对话框让其选择要放入的格子
            AssignOrderProductID();
            txtBarCode.Focus();
            txtBarCode.SelectAll();
        }

        /// <summary>
        /// 发音
        /// </summary>
        /// <param name="strMsg"></param>
        public void SpeekMsg(string strMsg, bool isNeedReadCompleted)
        {
            SpVoice Voice = new SpVoice();
            SpeechVoiceSpeakFlags SpFlags;


            if (isNeedReadCompleted)
            {
                Voice.Priority = SpeechVoicePriority.SVPAlert;
                SpFlags = SpeechVoiceSpeakFlags.SVSFDefault;

            }
            else
            {
                SpFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
            }

            try
            {
                Voice.Speak(strMsg, SpFlags);
            }
            catch { }
        }

        private void AssignOrderProductID()
        {
            string inputBarCode = txtBarCode.Text.Trim();
            string[] input = inputBarCode.Split(new char[] { '-' });
            if (input.Length != 2)
            {
                MessageBox.Show("输入的条码有误，应符合:定单号-字单号,请重新输入!");
                return;
            }
            int orderProductID, subOrderID;
            if (!Int32.TryParse(input[0], out orderProductID) || !Int32.TryParse(input[1], out subOrderID))
            {
                MessageBox.Show("请输入正确的条码，条码里应全为数字!不能包含其它非数字");
                return;
            }
            string gridName = string.Empty;
            bool IsNeedAssignNewGrid = false, IsAllEnd = false;
            int outPutStatus;


            using (SqlConnection con = new SqlConnection(strCon))
            {
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }
                var Command = con.CreateCommand();
                Command.CommandText = "AssignFactoryGrid";
                Command.CommandType = CommandType.StoredProcedure;
                Command.Parameters.Add(new SqlParameter("@orderProductID", orderProductID));
                Command.Parameters.Add(new SqlParameter("@subOrderID", subOrderID));

                Command.Parameters.Add(new SqlParameter("@GridName", SqlDbType.NVarChar, 50, ParameterDirection.Output, false, 0, 0, "GridName", DataRowVersion.Default, null));
                Command.Parameters.Add(new SqlParameter("@IsNeedAssign", SqlDbType.Bit, 0, ParameterDirection.Output, false, 0, 0, "IsNeedAssign", DataRowVersion.Default, null));
                Command.Parameters.Add(new SqlParameter("@isAllInGrid", SqlDbType.Bit, 0, ParameterDirection.Output, false, 0, 0, "isAllInGrid", DataRowVersion.Default, null));
                Command.Parameters.Add(new SqlParameter("@outPutStatus", SqlDbType.Int, 0, ParameterDirection.Output, false, 0, 0, "outPutStatus", DataRowVersion.Default, null));
                //@outPutStatus
                Command.ExecuteNonQuery();
                gridName = Command.Parameters["@GridName"].Value.ToString();
                IsNeedAssignNewGrid = Convert.ToBoolean(Command.Parameters["@IsNeedAssign"].Value);
                IsAllEnd = Convert.ToBoolean(Command.Parameters["@isAllInGrid"].Value);
                outPutStatus = Convert.ToInt32(Command.Parameters["@outPutStatus"].Value);
            }
            if (outPutStatus == 0)
            {
                MessageBox.Show("没有找到拆分记录.请先分单");
                return;
            }
            else if (outPutStatus == -1)
            {
                MessageBox.Show("合册已经完成");
                return;
            }

            if (IsAllEnd)//所有子产品都在格子中了，询问是否需要打印出来，清格
            {
                if (MessageBox.Show("产品的所有部件都已在格子" + gridName + "中，是否要打印清格", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    //行清格后打印
                    //PrintOrderInfo(orderProductID);
                    SetOrerComplete(orderProductID);
                    AssignGrid.PrintOrderInfo(orderProductID);

                }
                //刷新
                RushGridControl();
                return;
            }

            if (!IsNeedAssignNewGrid)
            {
                //读取格子号
                lblGridName.Text = gridName;

                SpeekMsg(gridName, true);
            }
            else
            {
                //跳出选择格子的界面
                int selectedGridID = 0;
                FrmSelectGrid frm = new FrmSelectGrid();
                frm.DTgrid = _dsResult.Tables[TBGRIDNAME];
                frm.InputProductCode = inputBarCode;
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    selectedGridID = frm.SelectedGridID;
                }
                if (selectedGridID > 0)
                {
                    using (SqlConnection con = new SqlConnection(strCon))
                    {
                        if (con.State == ConnectionState.Closed)
                        {
                            con.Open();
                        }
                        var Command1 = con.CreateCommand();
                        Command1.CommandText = "AssignFactoryIntoGrid";
                        Command1.CommandType = CommandType.StoredProcedure;
                        Command1.Parameters.Add(new SqlParameter("@orderProductID", orderProductID));
                        Command1.Parameters.Add(new SqlParameter("@subOrderID", subOrderID));
                        Command1.Parameters.Add(new SqlParameter("@GridID", selectedGridID));
                        //Command1.Parameters.Add(new SqlParameter("@isAllInGrid", IsAllEnd));
                        Command1.Parameters.Add(new SqlParameter("@isAllInGrid", SqlDbType.Bit, 0, ParameterDirection.Output, false, 0, 0, "isAllInGrid", DataRowVersion.Default, null));
                        Command1.Parameters.Add(new SqlParameter("@outPutStatus", SqlDbType.Int, 0, ParameterDirection.Output, false, 0, 0, "outPutStatus", DataRowVersion.Default, null));
                        Command1.ExecuteNonQuery();
                        IsAllEnd = Convert.ToBoolean(Command1.Parameters["@isAllInGrid"].Value);
                        //outPutStatus = Convert.ToInt32(Command1.Parameters["@outPutStatus"].Value);
                    }

                    if (IsAllEnd)//所有子产品都在格子中了，询问是否需要打印出来，清格
                    {
                        if (MessageBox.Show("产品的所有部件都已完成，是否要打印清格", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            //行清格后打印
                            //PrintOrderInfo(orderProductID);
                            SetOrerComplete(orderProductID);
                            AssignGrid.PrintOrderInfo(orderProductID);

                        }
                    }

                    MessageBox.Show("分配完成，请将产品放入" + frm.SelectedGridName + "格子中");

                }

                //刷新
                RushGridControl();
            }
        }

        private void SetOrerComplete(int orderProductID)
        {
            using (SqlConnection con = new SqlConnection(strCon))
            {
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }
                var Command1 = con.CreateCommand();
                Command1.CommandText = "SetOrderFactoryGridCompleted";
                Command1.CommandType = CommandType.StoredProcedure;
                Command1.Parameters.Add(new SqlParameter("@orderProductID", orderProductID));

                Command1.ExecuteNonQuery();
            }
        }

        private void FrmMain_KeyDown(object sender, KeyEventArgs e)
        {
            if (!txtBarCode.Focused)
            {
                txtBarCode.Focus();
            }
        }

        private void btnCX_Click(object sender, EventArgs e)
        {
            int orderProductId = 0;
            if (Int32.TryParse(txtCXorderProductId.Text.Trim(), out orderProductId))
            {
                if (orderProductId <= 0)
                {
                    return;
                }
                object result;
                //根据ORDERPRODUCTID找到该产品放到哪个格子里，如果产口已合册或是没有记录则提醒就好
                using (SqlConnection con = new SqlConnection(strCon))
                {
                    string strCX = "select gridName from grid where gridid= (select top 1 gridid from FactorySubOrderInfo where orderproductid=" + orderProductId + " and status =1)";
                    var command = con.CreateCommand();
                    result = command.ExecuteScalar();
                }
                if (result != null)
                {
                    MessageBox.Show("产品在" + result.ToString() + "格子中");
                }
                else
                {
                    MessageBox.Show("未在格子中找到该产品的组件");
                }
            }
            else
            {
                MessageBox.Show("请输入正确的产品号!");
            }

        }

    }
}
